package com.atguigu.tingshu.live.config;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.model.live.SocketMsg;
import jakarta.websocket.Session;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * title:
 * author: zgl
 * date: 2024/3/5
 * description：
 */
public class LiveRoomUtil {
    //用户id集合 key->roomId,value->userId列表
    private static Map<Long, List<Long>> idMap = new ConcurrentHashMap<>();
    //session集合 key->userId,value->Session列表
    private static Map<Long, Session> sessionMap = new ConcurrentHashMap<>();

    //添加用户
    public static void addUser(Long userId, Long roomId, Session session) {
        List<Long> ids = idMap.get(roomId);
        if (ids == null) {
            ids = new ArrayList<>();
            idMap.put(roomId, ids);
        }
        ids.add(userId);
        sessionMap.put(userId, session);
    }

    //删除用户
    public static void removeUser(Long roomId, Long userId) {
        List<Long> ids = idMap.get(roomId);
        if (ids == null) {
            return;
        }
        ids.remove(userId);
        sessionMap.remove(userId);
    }

    //获取用户列表
    public static List<Long> getUserList(Long roomId) {
        return idMap.get(roomId);
    }

    //在线人数
    public static Integer getUserCount(Long roomId) {
        List<Long> ids = idMap.get(roomId);
        if (ids == null) {
            return 0;
        }
        return ids.size();
    }

    //发送消息
    public static void sendMsg(String msg) {
        if (StringUtils.isBlank(msg)) {
            return;
        }
        SocketMsg socketMsg = JSON.parseObject(msg, SocketMsg.class);
        if (socketMsg == null || SocketMsg.MsgTypeEnum.HEART_BEAT.getCode().equals(socketMsg.getMsgType())) {
            return;
        }
        List<Long> ids = idMap.get(socketMsg.getLiveRoomId());
        if (ids == null) {
            return;
        }
        ids.forEach(id -> {
            Session sessions = sessionMap.get(id);
            if (sessions != null) {
                sessions.getAsyncRemote().sendText(msg);
            }
        });
    }
}
